const path = require('path');
const loginController = {};
const query = require('../model/query.js');
const session = require('express-session');
const md5 = require('md5');

const {
    password_secret
} = require('../config/config.js')

loginController.login = (req, res) => {
    res.render('login.html')
};

loginController.inLogins = async (req, res) => {
     
    let { username, password } = req.body;
    password = md5(`${password}${password_secret}`)
    const sql = `select * from users where username = '${username}' and password = '${password}'`;
    const result = await query(sql);
    if (result.length > 0) {
        //设置session
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000)
        });
        res.json({
            code: 0,
            message: '登录成功'
        })
    } else {
        // 失败则提示用户
        console.log(2);
        res.json({
            code: -2,
            message: "账号或密码错误"
        })
    }


};

loginController.outLogin = (req, res) => {
    //销毁session
    req.session.destroy(function (err) {
        if (err) {
            console.log(err);
        }
    })
    res.json({
        code: 0,
        message: "logout success"
    })
}


module.exports = loginController